package com.yidu.utils;


import org.apache.commons.lang.WordUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 导出word文档工具类
 * zyh
 */
@Component
public class FileExportTools {

    public static void Export2GeotechnicalLayeringTable(String template,Map<String, Object> map,int size, HttpServletResponse response,HttpServletRequest request){
        FileInputStream in = null;
        HWPFDocument  document = null;
        //获取当前项目工程路径
        String path=System.getProperty("user.dir");
        String templatePath=path+"\\src\\main\\resources\\static\\template\\"+template+"\\";
        System.out.println("路径"+templatePath);
        Date date = new Date();
        /*设置日期格式yyy-MM-dd hh:mm:ss*/
        SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd hh:mm:ss");
        response.setContentType("application/vnd.ms-word");
        response.setHeader("Content-Disposition", "attachment;filename="+sdf.format(date)+".doc");
        WordUtils wordUtils = new WordUtils();
        try {
            in = new FileInputStream(templatePath);
            document = new HWPFDocument(in);
            Range range=document.getRange();

            for(int i=1;i<=size;i++){
                range.replaceText("${"+i+"}",map.get(""+i).toString());
            }

            OutputStream os = response.getOutputStream();
            document.write(os);
            document.close();
            in.close();
            os.flush();
            os.close();
        }catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
